package com.tobestronger.shouxiespringframework.aop.framework;

import com.tobestronger.shouxiespringframework.aop.AdvisedSupport;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 基于 jdk动态代理 实现的AOP代理
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

    private final AdvisedSupport advised;

    public JdkDynamicAopProxy(AdvisedSupport advised) {
        this.advised = advised;
    }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                advised.getTargetSource().getTargetClassInterfaces(),
                this
            );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //判断是否是目标切点
        if (advised.getMethodMatcher().matches(method, advised.getTargetSource().getTargetClass())) {
            //是目标切点,执行方法拦截
            MethodInterceptor methodInterceptor = advised.getMethodInterceptor();
            return methodInterceptor.invoke(new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(), method, args));
        }
        //不是目标切点,正常执行原方法
        return method.invoke(advised.getTargetSource().getTarget(), args);
    }

}
